//
//  YSLevelView.m
//  Yueshi
//
//  Created by Northwan on 15/9/25.
//  Copyright © 2015年 悦食中国. All rights reserved.
//

#import "YSLevelView.h"

@interface YSLevelView()
@property (assign,nonatomic) LevelSourceType sourceType;
@end

@implementation YSLevelView

-(instancetype)initWithSourceType:(LevelSourceType)sourceType{
    if(self = [super init]){
        [self setBackgroundColor:[UIColor clearColor]];
        _sourceType = sourceType;
        for (int i = 1; i<=5; i++) {
            UIButton *starView = [UIButton new];
            
            if(sourceType == DetailSourceType){
                UIImage *img =  [UIImage imageNamed:@"btn_star_nor"];
                [starView setImage:img forState:UIControlStateNormal];
                [starView setImage:IMG(@"btn_star_pre_whole") forState:UIControlStateSelected];
            }else{
                UIImage *img =  [UIImage imageNamed:@"btn_star_gray"];
                [starView setImage:img forState:UIControlStateNormal];
                [starView setImage:IMG(@"btn_star_red") forState:UIControlStateSelected];
            }
             starView.tag = i;
            [starView addTarget:self action:@selector(tapScore:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:starView];
        }
    }
    return self;
}

-(void)setLevel:(NSInteger)level{
    _level = level;
    NSArray *starViews = self.subviews;
    for (int i = 0; i<starViews.count; i++) {
        UIButton *starView =  starViews[i];
        if(i+1 <= level){
            [starView setSelected:YES];
        }else{
            [starView setSelected:NO];
        }
    }
}

-(void)tapScore:(UIButton *)sender{
    [self setLevel:sender.tag];
    
    if([_delegate respondsToSelector:@selector(tapLevelCallBack:)]){
        [_delegate tapLevelCallBack:sender.tag];
    }
}

-(void)layoutSubviews{
    [super layoutSubviews];
    NSArray *starViews = self.subviews;
    for (int i = 0; i <starViews.count; i++) {
        UIButton *starView =  starViews[i];
        if(_sourceType == DetailSourceType){
            UIImage *img =  [UIImage imageNamed:@"btn_star_nor"];
            [starView setSize:img.size];
        }else{
            UIImage *img =  [UIImage imageNamed:@"btn_star_gray"];
            [starView setSize:img.size];
        }
        if(i == 0){
            starView.x = YSPublicXInset;
        }else{
            starView.x = CGRectGetMaxX(((UIButton *)starViews[i-1]).frame)+5;
        }
    }
    UIButton *starView = (UIButton *)[starViews lastObject];
    [self setSize:CGSizeMake(CGRectGetMaxX(starView.frame) , starView.height)];
}

@end
